package org.scs.carleton.ca.pgdt.core;

import java.io.File;
import java.io.FileNotFoundException;

import org.eclipse.core.resources.IResource;
import org.scs.carleton.ca.pgdt.core.internal.parser.ASTTranslationUnit;
import org.scs.carleton.ca.pgdt.core.internal.parser.Parser;
import org.scs.carleton.ca.pgdt.core.internal.parser.TokenMgrError;
import org.scs.carleton.ca.pgdt.core.parser.nodes.IASTProgram;
import org.scs.carleton.ca.pgdt.core.parser.nodes.IASTTranslationUnit;

/**
 * This is a provider class to obtain the AST Tree for documents
 * 
 * @author tessierj
 *
 */
public class ASTProvider {
	public ASTProvider() {
		
	}
	
	/**
	 * @param theDocument stringified version of the entire document
	 * @return
	 * @throws ParseException 
	 */
	public IASTProgram getProgram(String theDocument) throws ParseException, TokenMgrError {
		IASTProgram program;
		try {
			ASTTranslationUnit translationUnit = new ASTTranslationUnit(theDocument);
			Parser parser = new Parser(translationUnit);
			return parser.getProgram();
		}
		catch (FileNotFoundException e) {
			program = null;
		}
		
		return program;
	}
	
	/**
	 * Returns the AST for a certain resource
	 * 
	 * @param resource
	 * @return returns the knowledge base
	 * @throws ParseException 
	 */
	public IASTProgram getProgram(IResource resource) throws ParseException, TokenMgrError {
		IASTProgram program;
		try {
			File theFile = new File(resource.getRawLocation().toOSString());
			Parser parser = new Parser(new ASTTranslationUnit(theFile));
			program = parser.getProgram();
		}
		catch (FileNotFoundException e) {
			program = null;
		}
		
		return program;
	}
	
	/**
	 * Returns the Knowledge base for a certain translation unit
	 * 
	 * @param translationUnit
	 * @return
	 * @throws ParseException 
	 */
	public IASTProgram getProgram(IASTTranslationUnit translationUnit) throws ParseException {
		IASTProgram program;
		try {
			Parser parser = new Parser((ASTTranslationUnit)translationUnit);
			return parser.getProgram();
		}
		catch (FileNotFoundException e) {
			program = null;
		}
		
		return program;
	}
}
